package hot100;

public class Solution105 {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        return build(preorder, inorder, 0, preorder.length - 1, 0, inorder.length - 1);
    }

    public TreeNode build(int[] preorder, int[] inorder, int preStart, int preEnd, int inStart, int inEnd) {
        if (preStart > preEnd) return null;
        if (preStart == preEnd) return new TreeNode(preorder[preStart]);
        TreeNode root = new TreeNode(preorder[preStart]);
        int index = find(inorder, inStart, inEnd, root.val);
        root.left = build(preorder, inorder, preStart + 1, preStart + index - inStart, inStart, index - 1);
        root.right = build(preorder, inorder, preStart + index - inStart + 1, preEnd, index + 1, inEnd);
        return root;
    }

    public int find(int[] nums, int start, int end, int target) {
        for (int i = start; i <= end; i++) {
            if (nums[i] == target) return i;
        }
        return -1;
    }
}
